package com.gym.baselib.base

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.ToastUtils
import com.gym.baselib.utils.ProgressUtils

abstract class BaseFragment : Fragment() {

    private lateinit var launch: ActivityResultLauncher<Intent>
    private var mOnActivityResult:(Intent?)->Unit = {}

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        launch = registerForActivityResult(ActivityResultContracts.StartActivityForResult(), {
            if(it.resultCode == AppCompatActivity.RESULT_OK){
                mOnActivityResult(it.data)
            }
        })
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val rootView = inflater.inflate(getLayoutResId(), container, false)
        //ProgressUtils.init("$this")
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
    }

    @LayoutRes
    abstract fun getLayoutResId():Int

    abstract fun init()

    fun showProgress(){
        ProgressUtils.showProgress()
    }

    fun dismissProgress(){
        ProgressUtils.dismiss()
    }

    fun showToast(msg:String){
        ToastUtils.showShort(msg)
    }

    fun startActivityForResult(clazz:Class<*>,onActivityResult:(Intent?)->Unit){
        startActivityForResult(Intent(requireContext(),clazz),onActivityResult)
    }

    fun startActivityForResult(intent:Intent,onActivityResult:(Intent?)->Unit){
        mOnActivityResult = onActivityResult
        launch.launch(intent)
    }

}